﻿using Newtonsoft.Json;
using RXY_Mall.Api.Alipay;
using RXY_Mall.Api.Common;
using RXY_Mall.Api.Models;
using RXY_Mall.Core;
using RXY_Mall.Core.Tool;
using RXY_Mall.Data;
using RXY_Mall.Domain;
using RXY_Mall.Services.Finance;
using RXY_Mall.Services.Goods;
using RXY_Mall.Services.Order;
using RXY_Mall.Services.User;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Script.Serialization;
using WebApi.OutputCache.V2;

namespace RXY_Mall.Api.Controllers
{
    /// <summary>
    /// 订单接口
    /// </summary>
    [RoutePrefix("Order")]
    [ApiSecurityFilter]
    public class OrderController : BaseApiController
    {
        private RXY_MallContext db;
        private GoodsService goodsService;
        private OrderService orderService;
        private UserService userService;
        private FinanceService financeService;

        public OrderController()
        {
            db = new RXY_MallContext();
            goodsService = new GoodsService();
            orderService = new OrderService();
            userService = new UserService();
            financeService = new FinanceService();
        }

        /// <summary>
        /// 生成订单（第3批）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("AddOrder")]
        public async Task<Response<AddOrderOutput>> AddOrder(AddOrderInput input)
        {
            Response<AddOrderOutput> result = new Response<AddOrderOutput>();
            result.code = 0;
            result.msg = "";

            try
            {
                //判断用户
                var user = await db.gw_users.FirstOrDefaultAsync(u => u.id == input.user_id);
                if (user == null || user.deleted == true)
                {
                    result.msg = "该用户不存在";
                    return result;
                }
                if (user.status == 0)
                {
                    result.msg = "黑名单用户";
                    return result;
                }

                //防止重复刷单
                if (!PreventRepeatOrders(user.id))
                {
                    result.msg = "系统繁忙请稍后再试";
                    return result;
                }

                //判断地址
                var address = await db.gw_user_address_books.FindAsync(input.address_id);
                if (address == null)
                {
                    result.msg = "收货地址不存在";
                    return result;
                }
                if (address.user_id != input.user_id)
                {
                    result.msg = "收货地址不存在";
                    return result;
                }

                //购物车
                var carts = await db.gw_carts
                                .Include(g => g.gw_shop)
                                .Include(g => g.gw_goods_sku)
                                .Include(g => g.gw_goods)
                                .Include(g => g.gw_goods.gw_goods_property)
                                .Where(g => input.cart_ids.Contains(g.id) && g.user_id == input.user_id
                                && g.gw_goods_sku.is_sale && !g.gw_goods_sku.deleted
                                && !g.gw_goods.deleted && g.gw_goods.gw_goods_property.is_sale)
                                .ToListAsync();

                if (carts == null || carts.Count == 0)
                {
                    result.msg = "请添加商品";
                    return result;
                }
                input.buy_type = BuyType.CartBuy;

                var shop_ids = new List<int>();
                //商品
                List<gw_order_goods> order_goods = new List<gw_order_goods>();
                var company_id = 0;
                foreach (var cart in carts)
                {
                    if (!shop_ids.Contains(cart.shop_id))
                    {
                        shop_ids.Add(cart.shop_id);
                    }
                    order_goods.Add(new gw_order_goods()
                    {
                        shop_id = cart.shop_id,
                        category_id = cart.category_id,
                        sku_id = cart.gw_goods_sku.id,
                        api_unit = cart.gw_goods_sku.api_unit,
                        is_largess="N",
                        goods_id = cart.goods_id,
                        picture_url = cart.gw_goods_sku.thumb_url,
                        sku_specs = cart.gw_goods_sku.specs,
                        api_goods_id = cart.gw_goods.api_goods_id,
                        quantity = cart.quantity,
                        buy_type = (byte)input.buy_type,
                        goods_name = cart.gw_goods.name,
                        goods_type = cart.goods_type,
                        pay_price = (decimal)cart.gw_goods_sku.sale_price,
                        settlement_price = cart.gw_goods_sku.settlement_price,
                        conversion_rate = cart.conversion_rate,
                    });
                    if (cart.gw_shop.company_id != null)
                    {
                        company_id = (int)cart.gw_shop.company_id;
                    }
                }

                var open_id = "";
                //判断是否关注微信公众号
                if (input.pay_type == PayType.WeChatWeb)
                {
                    var third = user.gw_user_third.FirstOrDefault(t => t.type == 3);
                    if (third == null)
                    {
                        result.msg = "未绑定公众号";
                        return result;
                    }
                    open_id = third.open_id;
                }

                //判断库存
                decimal goods_total = 0m;
                int quantity = 0;
                Dictionary<int, int> dicSku = new Dictionary<int, int>();
                foreach (var goods in order_goods)
                {
                    //string error;

                    ////库存是否减少库存   
                    //if (!goodsService.ReduceSku(goods.sku_id, goods.quantity, out error))
                    //{
                    //    if (dicSku != null && dicSku.Count > 0)
                    //    {
                    //        //库存恢复
                    //        foreach (var item in dicSku.Keys)
                    //        {
                    //            goodsService.AddSku(item, dicSku[item], out error);
                    //        }
                    //    }
                    //    result.msg = error;
                    //    return result;
                    //}
                    //else
                    //{
                    //    dicSku.Add(goods.sku_id, goods.quantity);
                    //}
                    goods_total += goods.quantity * goods.pay_price;
                    quantity += goods.quantity;
                }

                string goodsType = "O";

                //添加订单
                var order_no = string.Format("G{0}{1}{2}", goodsType, input.buy_type.ToString().Substring(0, 1), Utils.GetOrderNumber());
                var order = new gw_order()
                {
                    order_no = order_no,
                    add_time = DateTime.Now,
                    beans = 0,
                    discounts = 0,
                    goods_count = quantity,
                    status = 1,
                    user_id = input.user_id,
                    pay_type = (int)input.pay_type,
                    pay_expire_time = DateTime.Now.AddMinutes(30),
                    order_status = (byte)OrderStatus2.待处理,
                    pay_status = (byte)PayStatus.未付款,
                    shipment_status = (byte)ShipmentStatus.未发货,
                    remark = input.remark,
                    goods_total = goods_total,
                    company_id = company_id,
                };
                if (shop_ids.Count == 1)
                {
                    order.shop_id = shop_ids[0];
                }
                db.gw_orders.Add(order);

                //优惠券

                //运费

                order.amount = order.goods_total + order.shipping_fee - order.discounts;
                if (order.amount < 0)
                {
                    order.amount = 0;
                }

                order.gw_order_goods = order_goods;

                //添加地址
                var orderAddress = new gw_order_address()
                {
                    accepter_name = address.accepter_name,
                    address = address.address,
                    address_id = address.id,
                    area = address.area,
                    city_code = address.city_code,
                    country_code = address.country_code,
                    email = address.email,
                    mobile = address.mobile,
                    post_code = address.post_code,
                    province_code = address.province_code,
                    telphone = address.telphone,
                };
                order.gw_order_address = orderAddress;

                //删除购物车
                List<int> cart_ids = new List<int>();
                foreach (var item in carts)
                {
                    cart_ids.Add(item.id);
                }
                await new CartController().DeleteCarts(new DeleteCartInput() { cart_ids = cart_ids, user_id = user.id });

                await db.SaveChangesAsync();

                string subject = "任销遥云商";
                string body = "";
                AddOrderOutput output = new AddOrderOutput();
                output.order_no = order_no;
                switch (input.pay_type)
                {
                    case PayType.Balance:
                        break;
                    case PayType.WeChatApp:
                        output.data = WxPayAPI.NativePay.GetPayUrl2(subject, body, order.order_no, (decimal)order.amount);
                        break;
                    case PayType.Alipay:
                        output.data = AlipayService.GetSign(order.order_no, body, subject, order.amount.ToString());
                        break;
                    case PayType.WeChatWeb:
                        output.data = new WxPayJSAPI.JsApiPay().GetUnifiedOrderResult2(subject, body, order.order_no, (decimal)order.amount, open_id);
                        break;
                    case PayType.WeChatH5:
                        output.data = new WxPayJSAPI.JsApiPay().GetUnifiedOrderResult2(subject, body, order.order_no, (decimal)order.amount, "");
                        break;
                }
                result.data = output;
                result.code = 1;
                result.msg = "下单成功";
                LogHelper.WriteLog(output.data);
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }

            return result;
        }

        /// <summary>
        /// 待支付订单可修改地址(第3批)
        /// </summary>
        [HttpPost]
        [Route("UpdateAddress")]
        public async Task<Response<bool>> UpdateAddress(UpdateAddressInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {
                //判断订单是否存在
                var isOrder = await orderService.IsExistOrder(input.order_no);
                if (!isOrder)
                {
                    result.msg = "订单不存在";
                    return result;
                }

                var order = await db.gw_orders
                    .Include(o => o.gw_order_address)
                    .FirstOrDefaultAsync(o => o.order_no == input.order_no && o.user_id == input.user_id && o.deleted == false);
                if (order == null)
                {
                    result.msg = "订单不存在";
                }

                //判断地址
                var address = await db.gw_user_address_books.FindAsync(input.address_id);
                if (address == null)
                {
                    result.msg = "收货地址不存在";
                    return result;
                }

                if (order.status == (int)OrderStatus.Pay)
                {
                    order.gw_order_address.accepter_name = address.accepter_name;
                    order.gw_order_address.address = address.address;
                    order.gw_order_address.address_id = address.id;
                    order.gw_order_address.area = address.area;
                    order.gw_order_address.city_code = address.city_code;
                    order.gw_order_address.country_code = address.country_code;
                    order.gw_order_address.email = address.email;
                    order.gw_order_address.mobile = address.mobile;
                    order.gw_order_address.post_code = address.post_code;
                    order.gw_order_address.province_code = address.province_code;
                    order.gw_order_address.telphone = address.telphone;

                    db.Entry(order.gw_order_address).State = EntityState.Modified;
                    await db.SaveChangesAsync();

                    result.code = 1;
                    result.data = true;
                    result.msg = "修改成功";
                    return result;
                }
                else
                {
                    result.msg = "未支付订单才可以修改地址";
                }
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }

            return result;
        }

        /// <summary>
        /// 余额支付订单（第3批）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PayOrderByBalance")]
        public async Task<Response<string>> PayOrderByBalance(PayOrderByBalanceInput input)
        {
            Response<string> result = new Response<string>();
            result.code = 0;
            result.msg = "";

            try
            {
                //该功能是否可以使用
                if (AppConfig.AppIsPay == 0)
                {
                    result.msg = "系统升级维护中，暂停消费，为您带来的不便敬请谅解";
                    return result;
                }

                #region 判断
                //判断用户
                var user = await db.gw_users
                    .Include(u => u.gw_finance_property)
                    .Include(u => u.gw_user_password)
                    .FirstOrDefaultAsync(u => u.id == input.user_id);
                if (user == null || user.deleted == true)
                {
                    result.msg = "该用户不存在";
                    return result;
                }
                if (user.status == 0)
                {
                    result.msg = "黑名单用户";
                    return result;
                }

                //判断支付密码是否正确
                string error = "";
                if (!userService.IsPassword(input.user_id, input.pay_password, 1, out error))
                {
                    result.msg = error;
                    return result;
                }
                #endregion

                #region 订单
                var pay_no = Utils.GetOrderNumber();

                #region 会员订单
                if (input.order_no.StartsWith("M000"))
                {
                    var orderMember = db.gw_order_members
                        .Include(o => o.gw_user)
                        .FirstOrDefault(b => b.order_no == input.order_no);
                    if (orderMember != null && orderMember.status == (int)OrderStatus.Pay)
                    {
                        //余额
                        if (user.gw_finance_property.balance < orderMember.amount)
                        {
                            result.msg = "余额不足,请选择其他方式";
                            return result;
                        }

                        //是否支付
                        if (!orderService.PayMemberOrder(orderMember, pay_no, out error))
                        {
                            result.msg = error;
                            return result;
                        }

                        //余额
                        user.gw_finance_property.balance -= orderMember.amount;
                        db.Entry(user.gw_finance_property).Property(p => p.balance).IsModified = true;

                        //余额记录
                        var log2 = new gw_finance_property_log()
                        {
                            add_time = DateTime.Now,
                            order_no = orderMember.order_no,
                            trade_type = (int)TradeType.在线支付,
                            currency = (byte)Currencies.Balance,
                            last_value = user.gw_finance_property.balance,
                            remark = string.Format("订单支付,余额减少{0}", orderMember.amount),
                            type = (int)PaymentType.Expense,
                            user_id = user.id,
                            value = orderMember.amount,
                        };
                        db.gw_finance_property_logs.Add(log2);

                        var now = DateTime.Now;
                        if (orderMember.gw_user.grade == (int)UserGrade.Ordinary)
                        {
                            orderMember.gw_user.grade = (int)UserGrade.Member;
                            orderMember.gw_user.start_time = now;
                            orderMember.gw_user.end_time = now.AddYears(orderMember.buy_year);

                            db.Entry(orderMember.gw_user).Property(o => o.grade).IsModified = true;
                            db.Entry(orderMember.gw_user).Property(o => o.start_time).IsModified = true;
                            db.Entry(orderMember.gw_user).Property(o => o.end_time).IsModified = true;
                        }
                        else
                        {
                            //判断是否过期
                            if (orderMember.gw_user.end_time != null && DateTime.Compare((DateTime)orderMember.gw_user.end_time, now) > 0)
                            {
                                var end = ((DateTime)orderMember.gw_user.end_time);
                                orderMember.gw_user.end_time = end.AddYears(orderMember.buy_year);
                            }
                            else
                            {
                                db.Entry(orderMember.gw_user).Property(o => o.grade).IsModified = true;
                                db.Entry(orderMember.gw_user).Property(o => o.start_time).IsModified = true;
                                db.Entry(orderMember.gw_user).Property(o => o.end_time).IsModified = true;
                            }
                        }

                        if (user.parent_id > 0)
                        {
                            //趣卡会员好友成为趣卡会员获贡献值
                            var parent = db.gw_users
                                .Include(u => u.gw_finance_property)
                                .FirstOrDefault(u => u.id == user.parent_id);

                            //直接购买实际支付金额获得1: 1贡献值
                            parent.gw_finance_property.exp += 200;
                            db.Entry(parent.gw_finance_property).Property(o => o.exp).IsModified = true;

                            //贡献值记录
                            var log3 = new gw_finance_property_log()
                            {
                                add_time = DateTime.Now,
                                order_no = "",
                                trade_type = (int)TradeType.趣卡会员好友成为趣卡会员获贡献值,
                                currency = (byte)Currencies.Exp,
                                last_value = parent.gw_finance_property.exp,
                                remark = string.Format("趣卡会员好友成为趣卡会员获贡献值,贡献值增加{0}", 200),
                                type = (int)PaymentType.Income,
                                user_id = parent.gw_finance_property.id,
                                value = 200,
                            };
                            db.gw_finance_property_logs.Add(log3);
                        }
                        orderMember.pay_no = pay_no;
                        orderMember.status = (int)OrderStatus.Complete;
                        orderMember.pay_time = DateTime.Now;
                        orderMember.pay_type = (int)PayType.Balance;

                        db.Entry(orderMember).Property(o => o.pay_no).IsModified = true;
                        db.Entry(orderMember).Property(o => o.status).IsModified = true;
                        db.Entry(orderMember).Property(o => o.pay_time).IsModified = true;
                        db.Entry(orderMember).Property(o => o.pay_type).IsModified = true;

                        db.SaveChanges();

                        var end_date = DateTime.Parse("2018-9-25");
                        if (end_date > DateTime.Now)
                        {
                            new UserController().AddUserCoupon(new AddUserCouponInput() { user_id = input.user_id, coupon_id = 84, });
                        }

                        result.msg = "支付成功";
                        result.code = 1;
                    }
                    return result;
                }
                #endregion

                #region 商品订单
                var order = await db.gw_orders
                   .Include(o => o.gw_order_goods)
                   //.Include(o => o.gw_order_group)
                   //.Include(o => o.gw_order_group.gw_order_group_user)
                   .FirstOrDefaultAsync(o => o.order_no == input.order_no);

                //过期 已支付
                if (order.status == (int)OrderStatus.Cancel)
                {
                    result.msg = "订单已取消";
                    return result;
                }

                if (order.user_id != input.user_id)
                {
                    result.msg = "订单不存在";
                    return result;
                }

                if (order.status != (int)OrderStatus.Pay && order.pay_type != (int)PayType.COD)
                {
                    result.msg = "订单已付款或取消";
                    return result;
                }

                if (order.status == (int)OrderStatus.Pay && order.pay_type != (int)PayType.COD)
                {
                    //判断订单是否过期
                    var date = DateTime.Now;
                    if (DateTime.Compare(date, order.pay_expire_time) > 0)
                    {
                        order.status = (int)OrderStatus.Cancel;
                        order.cancel_time = DateTime.Now;
                        db.Entry(order).State = EntityState.Modified;
                        await db.SaveChangesAsync();

                        result.msg = "订单已过期";
                        return result;
                    }
                }

                //判断余额是否足够
                if (user.gw_finance_property.balance < order.amount)
                {
                    result.msg = "余额不足,请选择其他方式";
                    return result;
                }

                //判断订单支付
                if (!orderService.PayOrder(order, pay_no, out error))
                {
                    result.msg = error;
                    return result;
                }

                order.status = (int)OrderStatus.Shipment;
                order.order_status = (byte)OrderStatus2.处理中;

                //扣余额
                user.gw_finance_property.balance -= order.amount;
                db.Entry(user.gw_finance_property).Property(p => p.balance).IsModified = true;

                //余额记录
                var log = new gw_finance_property_log()
                {
                    add_time = DateTime.Now,
                    order_no = order.order_no,
                    currency = (byte)Currencies.Balance,
                    last_value = user.gw_finance_property.balance,
                    remark = string.Format("订单支付,余额减少{0}", order.amount),
                    type = (int)PaymentType.Expense,
                    trade_type = (int)TradeType.在线支付,
                    user_id = user.id,
                    value = order.amount,
                };
                db.gw_finance_property_logs.Add(log);

                order.pay_no = pay_no;
                order.pay_time = DateTime.Now;
                order.pay_type = (int)PayType.Balance;
                order.pay_status = (byte)PayStatus.已付款;
                order.sync_status = 0;
                db.Entry(order).Property(o => o.status).IsModified = true;
                db.Entry(order).Property(o => o.order_status).IsModified = true;
                db.Entry(order).Property(o => o.pay_no).IsModified = true;
                db.Entry(order).Property(o => o.pay_time).IsModified = true;
                db.Entry(order).Property(o => o.pay_type).IsModified = true;
                db.Entry(order).Property(o => o.pay_status).IsModified = true;
                db.Entry(order).Property(o => o.sync_status).IsModified = true;

                #region 订单通知
                //订单支付通知
                gw_message messageOrder = new gw_message()
                {
                    add_time = DateTime.Now,
                    title = "支付成功通知",
                    summary = "上任销遥，用余额支付，多省一点！",
                    content = string.Format("订单号：{0}\n交易时间：{1}\n订单总价:{2}\n订单状态：支付成功", order.order_no, ((DateTime)order.pay_time).ToString("yyyy-MM-dd HH:mm:ss"), order.amount),
                    picture_url = order.gw_order_goods.FirstOrDefault().picture_url,
                    status = 1,
                    type = (int)MessageType.Order,
                    user_id = order.user_id,
                    company_id = order.company_id,
                };
                gw_message_rule_order messageRuleOrder = new gw_message_rule_order()
                {
                    order_id = order.id,
                    order_no = order.order_no,
                    order_status = order.status,
                };
                messageOrder.gw_message_rule_order = messageRuleOrder;
                db.gw_messages.Add(messageOrder);
                #endregion

                await db.SaveChangesAsync();
                #endregion

                #endregion

                //拆单功能
                orderService.SeparateOrder(order.id);

                result.code = 1;
                result.msg = "支付成功";
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 获取支付订单信息（第3批）
        /// </summary>
        [HttpGet]
        [Route("GetPayOrder")]
        public async Task<Response<string>> GetPayOrder(int user_id, string order_no, PayType pay_type)
        {
            Response<string> result = new Response<string>();
            result.code = 0;
            result.msg = "";

            try
            {
                var order = await db.gw_orders
                    .Include(o => o.gw_order_goods)
                    .FirstOrDefaultAsync(o => o.order_no == order_no && o.user_id == user_id && o.deleted == false);
                if (order == null)
                {
                    result.msg = "订单不存在";
                }

                if (order.status == (int)OrderStatus.Cancel)
                {
                    result.msg = "订单已取消";
                    return result;
                }
                if (order.status > 1)
                {
                    result.msg = "订单已支付";
                    return result;
                }

                if (order.status != (int)OrderStatus.Pay)
                {
                    result.msg = "订单状态不正确";
                    return result;
                }

                if (order.order_group_id != null)
                {
                    //是否可以参加拼单
                    string error = "";
                    if (!orderService.IsBuyGroup(order.user_id, (int)order.order_group_id, out error))
                    {
                        result.msg = error;
                        return result;
                    }
                }

                if (DateTime.Now > order.pay_expire_time)
                {
                    result.msg = "订单支付已过期";
                    return result;
                }

                //判断用户
                var user = await db.gw_users
                    .Include(u => u.gw_user_third)
                    .FirstOrDefaultAsync(u => u.id == user_id);
                if (user == null || user.deleted == true)
                {
                    result.msg = "该用户不存在";
                    return result;
                }

                if (user.status == 0)
                {
                    result.msg = "黑名单用户";
                    return result;
                }
                var open_id = "";
                //判断是否关注微信公众号
                if (pay_type == PayType.WeChatWeb)
                {
                    var third = user.gw_user_third.FirstOrDefault(t => t.type == 3);
                    if (third == null)
                    {
                        result.msg = "未绑定公众号";
                        return result;
                    }
                    open_id = third.open_id;
                }

                string subject = "任销遥云商";
                string body = order.gw_order_goods.FirstOrDefault().goods_name;
                switch (pay_type)
                {
                    case PayType.WeChatApp:
                        result.data = WxPayAPI.NativePay.GetPayUrl2(subject, body, order.order_no, (decimal)order.amount);
                        break;
                    case PayType.Alipay:
                        result.data = AlipayService.GetSign(order.order_no, body, subject, order.amount.ToString());
                        break;
                    case PayType.WeChatWeb:
                        result.data = new WxPayJSAPI.JsApiPay().GetUnifiedOrderResult2(subject, body, order.order_no, (decimal)order.amount, open_id);
                        break;
                    case PayType.WeChatH5:
                        result.data = new WxPayJSAPI.JsApiPay().GetUnifiedOrderResult2(subject, body, order.order_no, (decimal)order.amount, null);
                        break;
                    case PayType.COD:
                        //拆单功能

                        //货到付款
                        order.status = (byte)OrderStatus.Shipment;
                        order.pay_type = (byte)PayType.COD;
                        order.sync_status = 0;

                        db.Entry(order).Property(o => o.status).IsModified = true;
                        db.Entry(order).Property(o => o.pay_type).IsModified = true;
                        db.Entry(order).Property(o => o.sync_status).IsModified = true;
                        await db.SaveChangesAsync();

                        result.data = orderService.SeparateOrder(order.id);
                        break;
                    default:
                        result.data = order.order_no;
                        break;
                }
                result.code = 1;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 获得助力免单订单列表（第4批）
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <param name="page_index">页码</param>
        /// <param name="page_size">页数</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetFreeOrderList")]
        private Response<IPagedList<GetOrderListOutput>> GetFreeOrderList(int user_id, int page_index = 1, int page_size = 20)
        {
            return GetOrders(user_id, GroupType.Free, GroupRelation.All, OrderStatus.All, page_index, page_size);
        }

        /// <summary>
        /// 获得一元购订单列表
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <param name="page_index">页码</param>
        /// <param name="page_size">页数</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetWelfareOrderList")]
        private Response<IPagedList<GetOrderListOutput>> GetWelfareOrderList(int user_id, int page_index = 1, int page_size = 20)
        {
            return GetOrders(user_id, GroupType.Welfare, GroupRelation.All, OrderStatus.All, page_index, page_size);
        }

        /// <summary>
        /// 获得拼手气订单列表（第4批）
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <param name="group_relation">拼单关系</param>
        /// <param name="page_index">页码</param>
        /// <param name="page_size">页数</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetLuckyOrderList")]
        private Response<IPagedList<GetOrderListOutput>> GetLuckyOrderList(int user_id, GroupRelation group_relation = GroupRelation.Leader, int page_index = 1, int page_size = 20)
        {
            return GetOrders(user_id, GroupType.Lucky, group_relation, OrderStatus.All, page_index, page_size);
        }

        /// <summary>
        /// 获得订单列表（第3批）
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <param name="order_status">订单状态</param>
        /// <param name="page_index">页码</param>
        /// <param name="page_size">页数</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetOrderList")]
        public Response<IPagedList<GetOrderListOutput>> GetOrderList(int user_id, OrderStatus order_status = OrderStatus.All, int page_index = 1, int page_size = 20)
        {
            return GetOrders(user_id, GroupType.All, GroupRelation.All, order_status, page_index, page_size);
        }

        /// <summary>
        /// 获得所有订单
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <param name="group_type"></param>
        /// <param name="group_relation"></param>
        /// <param name="order_status"></param>
        /// <param name="page_index"></param>
        /// <param name="page_size"></param>
        /// <returns></returns>
        private Response<IPagedList<GetOrderListOutput>> GetOrders(int user_id, GroupType group_type = GroupType.All, GroupRelation group_relation = GroupRelation.All, OrderStatus order_status = OrderStatus.All, int page_index = 1, int page_size = 20)
        {
            Response<IPagedList<GetOrderListOutput>> result = new Response<IPagedList<GetOrderListOutput>>();
            result.code = 0;
            result.msg = "";

            try
            {
                var date = DateTime.Now;
                var sources = db.gw_orders
                    .Include(o => o.gw_return)
                    .Include(o => o.gw_order_goods)
                    .Where(o => o.user_id == user_id && o.deleted == false && o.status != (byte)OrderStatus.Separate)
                    .Select(o => new GetOrderListOutput()
                    {
                        _add_time = o.add_time,
                        order_no = o.order_no,
                        order_status = (OrderStatus)o.status,
                        pay_status = (PayStatus)o.pay_status,
                        pay_expire_time = o.pay_expire_time,
                        amount = o.amount.ToString(),
                        discounts = o.discounts.ToString(),
                        shipping_fee = o.shipping_fee.ToString(),
                        goods_count = o.goods_count,
                        goods_total = o.goods_total,
                        pay_type = (PayType)o.pay_type,
                    });

                if (order_status != OrderStatus.All)
                {
                    sources = sources.Where(o => o.order_status == order_status);
                    //待分享
                    if (order_status == OrderStatus.Group)
                    {
                        //sources = sources.Where(o => o.gw_order_group.expire_time > date);
                    }
                    //待付款
                    else if (order_status == OrderStatus.Pay)
                    {
                        sources = sources.Where(o => o.pay_expire_time > date);
                    }
                }

                sources = sources.OrderByDescending(s => s._add_time);
                IPagedList<GetOrderListOutput> output = new PagedList<GetOrderListOutput>(sources, page_index, page_size);

                foreach (var item in output)
                {
                    item.add_time = TimeHelper.GetTimeStamp(item._add_time);
                    //待付款
                    if (date > item.pay_expire_time && item.order_status == OrderStatus.Pay)
                    {
                        item.order_status = OrderStatus.Cancel;
                        //
                        //orderService.ServiceCancelOrder(item.order_no);
                    }
                }

                result.data = output;
                result.code = 1;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 获得订单数量
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetOrderCount")]
        public async Task<Response<GetOrderCountOutput>> GetOrderCount(int user_id)
        {
            Response<GetOrderCountOutput> result = new Response<GetOrderCountOutput>();
            result.code = 0;
            result.msg = "";
            try
            {
                var date = DateTime.Now.AddMonths(-1);
                var orderStatus = await db.gw_orders
                    .Include(g => g.gw_order_goods)
                    .Where(o => o.add_time > date && o.user_id == user_id && !o.deleted)
                    .GroupBy(o => new { o.status, o.gw_order_goods.FirstOrDefault().goods_type })
                    .Select(o => new
                    {
                        o.Key.status,
                        o.Key.goods_type,
                        count = o.Count()
                    })
                    .ToListAsync();

                List<int> lstStatus = new List<int>();
                lstStatus.Add((int)ReturnStatus.已完成);
                lstStatus.Add((int)ReturnStatus.已取消);
                lstStatus.Add((int)ReturnStatus.审核失败);

                var returnCount = await db.gw_returns
                    .CountAsync(r => r.add_time > date && r.user_id == user_id && !lstStatus.Contains(r.status) && !r.deleted);

                GetOrderCountOutput output = new GetOrderCountOutput();
                foreach (var item in orderStatus)
                {
                    var status = (OrderStatus)item.status;
                    switch (status)
                    {
                        case OrderStatus.Pay:
                            if (item.goods_type == (int)GoodsType.Welfare)
                            {
                                continue;
                            }
                            output.PayCount += item.count;
                            break;
                        case OrderStatus.Group:
                            //if (item.goods_type == (int)GoodsType.Free || item.goods_type == (int)GoodsType.Welfare)
                            //{
                            //    continue;
                            //}
                            //output.GroupCount += item.count;
                            break;
                        case OrderStatus.Failure:
                            output.FailureCount += item.count;
                            break;
                        case OrderStatus.Shipment:
                            output.ShipmentCount += item.count;
                            break;
                        case OrderStatus.Receive:
                            output.ReceiveCount += item.count;
                            break;
                        //case OrderStatus.Comment:
                        //    output.CommentCount += item.count;
                        //    break;
                        case OrderStatus.Complete:
                            output.CompleteCount += item.count;
                            break;
                        case OrderStatus.Cancel:
                            output.CancelCount += item.count;
                            break;
                        default:
                            break;
                    }
                }
                output.ReturnCount = returnCount;

                result.code = 1;
                result.data = output;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 获得订单详情（第3批）
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <param name="order_no">订单号</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetOrder")]
        public async Task<Response<GetOrderOutput>> GetOrder(int user_id, string order_no)
        {
            Response<GetOrderOutput> result = new Response<GetOrderOutput>();
            result.code = 0;
            result.msg = "";

            try
            {
                //判断订单是否存在
                var isOrder = await orderService.IsExistOrder(order_no);
                if (!isOrder)
                {
                    result.msg = "订单不存在";
                    return result;
                }

                var order = await db.gw_orders
                    .Include(o => o.gw_return)
                    .Include(o => o.gw_order_address)
                    .Include(o => o.gw_order_goods)
                    .Include(o => o.gw_order_waybill)
                    .Where(o => o.user_id == user_id && o.deleted == false && o.order_no == order_no)
                    .Select(item => new GetOrderOutput()
                    {
                        //_group_time = item.group_time,
                        _pay_time = item.pay_time,
                        _receive_time = item.receive_time,
                        _shipment_time = item.shipment_time,
                        _cancel_time = item.cancel_time,
                        _complete_time = item.complete_time,
                        //_comment_time = item.comment_time,

                        _add_time = item.add_time,
                        pay_expire_time = item.pay_expire_time,
                        order_no = item.order_no,
                        order_status = (OrderStatus)item.status,
                        amount = item.amount.ToString(),
                        discounts = item.discounts.ToString(),
                        shipping_fee = item.shipping_fee.ToString(),
                        pay_type = (PayType)item.pay_type,
                        remark = item.remark,

                        goods = item.gw_order_goods.Select(g => new OrderGoods()
                        {
                            category_id = g.category_id,
                            goods_id = g.goods_id,
                            goods_name = g.goods_name,
                            goods_type = (GoodsType)g.goods_type,
                            json_specs = g.sku_specs,
                            buy_type = (BuyType)g.buy_type,
                            goods_price = g.pay_price.ToString(),
                            goods_quantity = g.quantity,
                            picture_url = g.picture_url,
                        }).ToList(),

                        address = new OrderAddress()
                        {
                            address = item.gw_order_address.address,
                            accepter_name = item.gw_order_address.accepter_name,
                            area = item.gw_order_address.area,
                            mobile = item.gw_order_address.mobile,
                        },

                        gw_order_waybill = item.gw_order_waybill,
                        //gw_order_group = item.gw_order_group,
                        //is_leader = item.gw_order_group == null ? true : item.gw_order_group.gw_order_group_user.Any(u => u.is_leader == true && u.user_id == user_id),
                        //return_order = item.gw_return.Where(r => r.deleted == false).Select(r => new ReturnOrder()
                        //{
                        //    return_no = r.return_no,
                        //    is_return_request = r.status > 10,
                        //}).FirstOrDefault(),

                        //service_status = item.service_status,
                        //service_expire_time = item.service_expire_time,

                    }).FirstOrDefaultAsync();

                var date = DateTime.Now;
                if (order != null)
                {

                    order.add_time = TimeHelper.GetTimeStamp(order._add_time);
                    order.pay_time = TimeHelper.GetTimeStamp(order._pay_time);
                    //order.group_time = TimeHelper.GetTimeStamp(order._group_time);
                    order.shipment_time = TimeHelper.GetTimeStamp(order._shipment_time);
                    order.receive_time = TimeHelper.GetTimeStamp(order._receive_time);
                    order.cancel_time = TimeHelper.GetTimeStamp(order._cancel_time);
                    order.complete_time = TimeHelper.GetTimeStamp(order._complete_time);
                    //order.comment_time = TimeHelper.GetTimeStamp(order._comment_time);

                    foreach (var item in order.goods)
                    {
                        item.specs = JsonConvert.DeserializeObject<List<SpecOutput>>(item.json_specs);
                        item.picture_url = HostHelper.GetImgUrl(item.picture_url);
                    }

                    //待付款
                    if (date > order.pay_expire_time && order.order_status == OrderStatus.Pay)
                    {
                        order.order_status = OrderStatus.Cancel;
                    }

                    if (order.gw_order_waybill != null)
                    {
                        order.waybill = new Waybill()
                        {
                            company_name = order.gw_order_waybill.company_name,
                            telphone = order.gw_order_waybill.telphone,
                            waybill_no = order.gw_order_waybill.waybill_no,
                        };
                    }

                    #region 拼单
                    //if (order.gw_order_group != null)
                    //{
                    //    order.group = new OrderGroupOutput()
                    //    {
                    //        add_time = TimeHelper.GetTimeStamp(order.gw_order_group.add_time),
                    //        cancel_time = TimeHelper.GetTimeStamp(order.gw_order_group.cancel_time),
                    //        complete_time = TimeHelper.GetTimeStamp(order.gw_order_group.complete_time),
                    //        expire_time = TimeHelper.GetTimeStamp(order.gw_order_group.expire_time),
                    //        group_status = (GroupStatus)order.gw_order_group.status,
                    //        group_type = (GroupType)order.gw_order_group.group_type,
                    //        is_red_packet = order.gw_order_group.is_red_packet,
                    //        require_num = order.gw_order_group.require_num,
                    //        order_group_id = order.gw_order_group.id,
                    //        order_group_no = order.gw_order_group.group_no,
                    //        is_leader = order.is_leader,
                    //        red_packet = (float)order.gw_order_group.red_packet,
                    //        //user_num = order.user_num,
                    //        group_users = order.gw_order_group.gw_order_group_user.OrderBy(u => u.add_time).Select(u => new GroupUser
                    //        {
                    //            order_id = u.order_id,
                    //            user_id = u.user_id,
                    //            acquire_red_packet = u.acquire_red_packet,
                    //            acquire_time = TimeHelper.GetTimeStamp(u.acquire_time),
                    //            add_time = TimeHelper.GetTimeStamp(u.add_time),
                    //            help_state = u.help_status,
                    //            is_award = u.is_award,
                    //            is_leader = u.is_leader,
                    //            logo = u.gw_user.logo,
                    //            nick_name = u.gw_user.nick_name == null ? StringHelper.HideMobile(u.gw_user.name) : u.gw_user.nick_name,
                    //        }).ToList(),

                    //    };

                    //    //待分享
                    //    if (date > order.gw_order_group.expire_time && order.group.group_status == GroupStatus.Process)
                    //    {
                    //        order.group.group_status = GroupStatus.Failure;
                    //        order.order_status = OrderStatus.Failure;
                    //    }

                    //    //拼手气-获得红包、拼单成功
                    //    if (order.group.group_type == GroupType.Lucky && order.group.group_status == GroupStatus.Succeed)
                    //    {
                    //        var group_user = order.group.group_users.FirstOrDefault(u => u.user_id == user_id && !(bool)u.is_award);
                    //        if (group_user != null)
                    //        {
                    //            //红包ID 红包类型
                    //            var redpacket = db.gw_finance_redpackets
                    //                .FirstOrDefault(r => r.user_id == group_user.user_id && r.order_id == group_user.order_id);
                    //            if (redpacket != null)
                    //            {
                    //                order.group.redpacket = new GetRedpacketOutput()
                    //                {
                    //                    redpacket_id = redpacket.id,
                    //                    redpacket_type = (RedpacketType)redpacket.type,
                    //                    is_acquire = redpacket.is_acquire
                    //                };
                    //            }
                    //        }
                    //    }
                    //}
                    #endregion

                    #region 售后
                    //售后
                    //if (order.service_status != null)
                    //{
                    //    if (order.return_order == null)
                    //    {
                    //        order.return_order = new ReturnOrder()
                    //        {
                    //            is_return_request = false,
                    //        };
                    //    }
                    //    if (order.service_status == (int)ServiceStatus.可申请售后 && order.service_expire_time > DateTime.Now)
                    //    {
                    //        order.return_order.is_return_request = true;
                    //    }
                    //    if (order.service_status != (byte)ServiceStatus.可申请售后)
                    //    {
                    //        order.return_order.is_return_request = false;
                    //    }
                    //}
                    #endregion
                }
                result.code = 1;
                result.data = order;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 取消订单（第3批）
        /// </summary>
        [HttpPost]
        [Route("CancelOrder")]
        public Response<bool> CancelOrder(CancelOrderInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {
                var error = "";
                if (orderService.CancelOrder(input.order_no, out error, input.user_id))
                {
                    result.code = 1;
                    result.data = true;
                    return result;
                }
                else
                {
                    result.msg = error;
                    result.code = 0;
                    return result;
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 确认收货（第3批）
        /// </summary>
        [HttpPost]
        [Route("ReceiveOrder")]
        public async Task<Response<bool>> ReceiveOrder(CancelOrderInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {
                //判断订单是否存在
                var isOrder = await orderService.IsExistOrder(input.order_no);
                if (!isOrder)
                {
                    result.msg = "订单不存在";
                    return result;
                }

                var order = await db.gw_orders.FirstOrDefaultAsync(o => o.order_no == input.order_no && o.user_id == input.user_id && o.deleted == false);
                if (order == null)
                {
                    result.msg = "订单不存在";
                }

                if (order.status == (int)OrderStatus.Receive)
                {
                    order.status = (int)OrderStatus.Complete;
                    order.receive_time = DateTime.Now;
                    order.order_status = (byte)OrderStatus2.已完成;
                    order.shipment_status = (byte)ShipmentStatus.已交货;
                    order.service_status = (byte)ServiceStatus.可申请售后;
                    order.service_expire_time = DateTime.Now.AddDays(7);

                    db.Entry(order).Property(o => o.status).IsModified = true;
                    db.Entry(order).Property(o => o.receive_time).IsModified = true;
                    db.Entry(order).Property(o => o.order_status).IsModified = true;
                    db.Entry(order).Property(o => o.shipment_status).IsModified = true;
                    db.Entry(order).Property(o => o.service_status).IsModified = true;
                    db.Entry(order).Property(o => o.service_expire_time).IsModified = true;

                    await db.SaveChangesAsync();

                    result.code = 1;
                    result.data = true;
                    return result;
                }
                else
                {
                    result.msg = "订单状态不正确";
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 删除订单（第3批）
        /// </summary>
        [HttpPost]
        [Route("DeleteOrder")]
        public async Task<Response<bool>> DeleteOrder(CancelOrderInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {
                //判断订单是否存在
                var isOrder = await orderService.IsExistOrder(input.order_no);
                if (!isOrder)
                {
                    result.msg = "订单不存在";
                    return result;
                }

                var order = await db.gw_orders.FirstOrDefaultAsync(o => o.order_no == input.order_no && o.user_id == input.user_id && o.deleted == false);
                if (order == null)
                {
                    result.msg = "订单不存在";
                    return result;
                }

                if (order.status == (int)OrderStatus.Pay || order.status == (int)OrderStatus.Cancel || order.status == (int)OrderStatus.Complete || order.status == (int)OrderStatus.Failure)
                {
                    order.deleted = true;

                    await db.SaveChangesAsync();

                    result.code = 1;
                    result.data = true;
                    result.msg = "删除订单成功";
                    return result;
                }
                else
                {
                    result.msg = "订单状态不正确";
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 购买会员(第4批)
        /// </summary>
        /// <param name="input">地址信息输入信息</param>
        /// <returns>data:地址ID</returns>
        [HttpPost]
        [Route("AddMemberOrder")]
        private async Task<Response<string>> AddMemberOrder(AddMemberOrderInput input)
        {
            Response<string> result = new Response<string>();
            result.code = 0;
            result.msg = "";
            try
            {
                var member_price = 298m;
                var member_promote_price = 298m;
                var member_prices = await db.gw_settings.Where(s => s.name.Contains("member_")).ToListAsync();
                if (member_prices != null)
                {
                    var str_member_price = member_prices.FirstOrDefault(s => s.name == "member_price").value;
                    var str_member_promote_price = member_prices.FirstOrDefault(s => s.name == "member_promote_price").value;
                    if (!string.IsNullOrWhiteSpace(str_member_price))
                    {
                        member_price = decimal.Parse(str_member_price);
                    }
                    if (!string.IsNullOrWhiteSpace(str_member_promote_price))
                    {
                        member_promote_price = decimal.Parse(str_member_promote_price);
                    }
                }

                if (!PreventRepeatOrders(input.user_id))
                {
                    result.msg = "系统繁忙请稍后再试";
                    return result;
                }

                var user = await db.gw_users.Include(u => u.gw_user_third).FirstOrDefaultAsync(u => u.id == input.user_id);
                var open_id = "";
                //判断是否关注微信公众号
                if (input.pay_type == PayType.WeChatWeb)
                {
                    var third = user.gw_user_third.FirstOrDefault(t => t.type == 3);
                    if (third == null)
                    {
                        result.msg = "未绑定公众号";
                        return result;
                    }
                    open_id = third.open_id;
                }

                var order_no = string.Format("M000{0}{1}{2}", 1, (int)input.pay_type, Utils.GetOrderNumber());
                gw_order_member orderMember = new gw_order_member()
                {
                    order_no = order_no,
                    user_id = input.user_id,
                    add_time = DateTime.Now,
                    buy_type = 1,
                    buy_year = 1,
                    year_money = member_promote_price,
                    amount = member_promote_price,
                    pay_type = (int)input.pay_type,
                    status = 1,
                };

                db.gw_order_members.Add(orderMember);
                int row = await db.SaveChangesAsync();

                string subject = "任销遥云商";
                string body = "趣卡会员";
                switch (input.pay_type)
                {
                    case PayType.Balance:
                        result.data = orderMember.order_no;
                        break;
                    case PayType.WeChatApp:
                        result.data = WxPayAPI.NativePay.GetPayUrl2(subject, body, orderMember.order_no, orderMember.amount);
                        break;
                    case PayType.Alipay:
                        result.data = AlipayService.GetSign(orderMember.order_no, body, subject, orderMember.amount.ToString());
                        break;
                    case PayType.WeChatWeb:
                        result.data = new WxPayJSAPI.JsApiPay().GetUnifiedOrderResult2(subject, body, orderMember.order_no, (decimal)orderMember.amount, open_id);
                        break;
                    case PayType.WeChatH5:
                        result.data = new WxPayJSAPI.JsApiPay().GetUnifiedOrderResult2(subject, body, orderMember.order_no, (decimal)orderMember.amount, "");
                        break;
                    case PayType.COD:

                        break;
                }

                result.code = 1;
                result.msg = "下单成功";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
            }
            return result;
        }

        #region 快递
        /// <summary>
        /// 快递100实时快递查询接口
        /// </summary>
        /// <param name="com">查询的快递公司的编码， 一律用小写字母</param>
        /// <param name="num">查询的快递单号， 单号的最大长度是32个字符</param>
        /// <returns></returns>
        [CacheOutput(ClientTimeSpan = 60, ServerTimeSpan = 60)]
        private WaybillInfo GetExpressTrack(string com, string num)
        {
            string url = "https://poll.kuaidi100.com/poll/query.do";

            //参数
            String param = "{\"com\":\"" + com + "\",\"num\":\"" + num + "\",\"from\":\"\",\"to\":\"\"}";
            String customer = "155726E761721A78AA07B2A742EEC131";
            String key = "wuDuANPS1704";
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] InBytes = Encoding.GetEncoding("UTF-8").GetBytes(param + key + customer);
            byte[] OutBytes = md5.ComputeHash(InBytes);
            string OutString = "";
            for (int i = 0; i < OutBytes.Length; i++)
            {
                OutString += OutBytes[i].ToString("x2");
            }
            String sign = OutString.ToUpper();
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("param", param);
            parameters.Add("customer", customer);
            parameters.Add("sign", sign);
            string paramjson = JsonConvert.SerializeObject(parameters);
            var result = WebUtils.CreatePostHttpResponse(url, parameters);

            JavaScriptSerializer jss = new JavaScriptSerializer();
            WaybillInfo info = jss.Deserialize<WaybillInfo>(result);
            return info;
        }

        /// <summary>
        /// 获得订单轨迹
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <param name="order_no">订单号</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetOrderTrack")]
        public Response<GetOrderTrackOutput> GetOrderTrack(int user_id, string order_no)
        {
            Response<GetOrderTrackOutput> result = new Response<GetOrderTrackOutput>();
            result.code = 0;
            try
            {
                bool muti = true;
                bool isDesc = true;

                var order = db.gw_orders.Include(o => o.gw_order_waybill).FirstOrDefault(o => o.order_no == order_no);
                if (order.user_id != user_id)
                {
                    LogHelper.WriteLog(string.Format("无权限，加入黑名单：用户ID：{0}，订单号：{1}", user_id, order_no));
                    result.msg = "无权限";
                    return result;
                }
                if (order.gw_order_waybill == null)
                {
                    result.msg = "请等待发货";
                    return result;
                }

                //数据库查询 如果签收就直接返回信息
                var express = db.gw_base_logistics.FirstOrDefault(l => l.name == order.gw_order_waybill.company_name);
                if (express == null)
                {
                    result.msg = "抱歉，暂无查询记录";
                    return result;
                }

                string express_code = express.code;

                WaybillInfo info = GetExpressTrack(express_code, order.gw_order_waybill.waybill_no);

                GetOrderTrackOutput expressInfo = new GetOrderTrackOutput();
                expressInfo.waybill_no = order.gw_order_waybill.waybill_no;
                expressInfo.express_name = order.gw_order_waybill.company_name;
                expressInfo.telephone = express.telephone;
                expressInfo.express_code = express_code;
                expressInfo.status = info.state;
                expressInfo.html_status = info.status;
                if (info.message == "ok")
                {
                    List<WaybillDetail> details = info.data;
                    DateTime starTime = details[0].time;
                    DateTime endTime = details[details.Count - 1].time;
                    TimeSpan ts = starTime.Subtract(endTime);
                    double totalHours = ts.TotalHours;
                    expressInfo.days = ((int)totalHours / 24).ToString() + "天" + ((int)totalHours % 24).ToString() + "小时";
                    expressInfo.message = "OK";
                    List<WaybillDetail> dd = details;
                    if (muti)
                    {
                        if (isDesc)
                        {
                            List<TrackDetail> kdList = new List<TrackDetail>();
                            foreach (WaybillDetail t in dd)
                            {
                                TrackDetail kd = new TrackDetail() { time = t.time.ToString(), timestamp = TimeHelper.GetTimeStamp(t.time), context = t.context };
                                kdList.Add(kd);
                            }
                            expressInfo.detail = kdList;
                        }
                        else
                        {
                            dd = dd.OrderBy(p => p.time).ToList();
                            List<TrackDetail> kdList = new List<TrackDetail>();
                            foreach (WaybillDetail t in dd)
                            {
                                TrackDetail kd = new TrackDetail() { time = t.time.ToString(), timestamp = TimeHelper.GetTimeStamp(t.time), context = t.context };
                                kdList.Add(kd);
                            }
                            expressInfo.detail = kdList;
                        }
                    }
                    else
                    {
                        if (isDesc)
                        {
                            TrackDetail kd = new TrackDetail() { time = dd[0].time.ToString(), timestamp = TimeHelper.GetTimeStamp(dd[0].time), context = dd[0].context };
                            List<TrackDetail> kdList = new List<TrackDetail>();
                            kdList.Add(kd);
                            expressInfo.detail = kdList;
                        }
                        else
                        {
                            dd = dd.OrderBy(p => p.time).ToList();
                            TrackDetail kd = new TrackDetail() { time = dd[0].time.ToString(), timestamp = TimeHelper.GetTimeStamp(dd[0].time), context = dd[0].context };
                            List<TrackDetail> kdList = new List<TrackDetail>();
                            kdList.Add(kd);
                            expressInfo.detail = kdList;
                        }
                    }

                    result.code = 1;
                    result.data = expressInfo;
                }
                else
                {
                    var messages = info.message.Split('：');
                    expressInfo.message = messages.Length > 1 ? messages[1] : messages[0];
                    result.msg = expressInfo.message;
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        #endregion

        /// <summary>
        /// 防止重复下单
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns></returns>
        private bool PreventRepeatOrders(int user_id)
        {
            var flag = true;
            if (CommonHelper.DownloadOrder.Keys.Contains(user_id))
            {
                if (CommonHelper.DownloadOrder[user_id] > DateTime.Now.AddSeconds(-3))
                {
                    flag = false;
                }
                else
                {
                    CommonHelper.DownloadOrder[user_id] = DateTime.Now;
                }
            }
            else
            {
                CommonHelper.DownloadOrder.Add(user_id, DateTime.Now);
            }
            return flag;
        }
    }
}
